package com.qd.system.service.person;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.sys.constant.Constants;
import com.qd.common.sys.domain.entity.person.PersonDTO;
import com.qd.system.mapper.PersonMapper;
import com.qd.system.model.Person;
import com.qd.system.service.dict.MbUtil;
import com.qd.system.service.org.OrgService;
import com.qd.system.service.user.UserOperatorService;
import com.qd.system.util.FileConfirmUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * @author sjk
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class PersonService extends BaseService<PersonMapper, Person> {

    private static final String PREFIX_ID = "sys_person_personId_{0}";
    private static final String PREFIX_UNIQUE_SYS_PERSON = "sys_person_personId_{0}_orgId_{1}";

    private final RedisTemplateUtil<Person> redisTemplateUtil;
    private final OrgService orgService;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public PersonDTO save(PersonDTO dto) {
        checkUnique(dto);
        final Person model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public PersonDTO update(PersonDTO dto) {
        checkUnique(dto);
        final Person historyModel = Optional.ofNullable(getById(dto.getPersonId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final Person model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(model);
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 删除，单个
     *
     * @param personId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String personId) {
        final Person model = Optional.ofNullable(getById(personId)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(personId)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        List<Person> historyModelList = checkIds(ids);
        try {
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(PersonDTO dto) {
        final QueryWrapper<Person> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param personId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String personId) {
        boolean exists = false;
        if (StringUtils.hasLength(personId)) {
            final Person model = getById(personId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param personId 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public Person getById(String personId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, personId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(personId), Person.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param personId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public PersonDTO getByIdDto(String personId) {
        final Person model = getById(personId);
        if (null != model) {
            return modelToDto(model);
        }
        return null;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public Person getOne(PersonDTO dto) {
        final QueryWrapper<Person> queryWrapper = createQueryWrapper(dto);
        Person model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public PersonDTO getOneDto(PersonDTO dto) {
        final Person model = getOne(dto);
        if (null == model) {
            return null;
        }
        final PersonDTO newDto = modelToDto(model);
        model.freeData();
        return newDto;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<Person> getList(PersonDTO dto) {
        final QueryWrapper<Person> queryWrapper = createQueryWrapper(dto);
        final List<Person> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<PersonDTO> getListDto(PersonDTO dto) {
        return modelToDtoList(getList(dto));
    }


    @Transactional(readOnly = true)
    public IPage<PersonDTO> basePage(Page<Person> page, PersonDTO dto, boolean isSesPwd) {
        final QueryWrapper<Person> queryWrapper = createQueryWrapper(dto, "p.");
        UserOperatorService.buildInSql(dto, queryWrapper);
        final IPage<PersonDTO> iPage = baseMapper.page(page, queryWrapper, isSesPwd);
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 根据唯一性索引获得数据
     * <p>
     * param personId
     * param orgId
     *
     * @return 单条数据
     */
    @Transactional(readOnly = true)
    public Person getUniqueByPersonIdAndOrgId(String personId, String orgId) {
        final QueryWrapper<Person> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.PERSON_ID, personId);
        queryWrapper.eq(Constants.ORG_ID, orgId);
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_SYS_PERSON, personId, orgId);
        final Person model = redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getOne(queryWrapper, false), Person.class);
        queryWrapper.clear();
        return model;
    }

    /**
     * 验证唯一性索引
     *
     * @param dto 页面对象
     */
    private void checkUnique(PersonDTO dto) {
        final Person model = getUniqueByPersonIdAndOrgId(dto.getPersonId(), dto.getOrgId());
        if (null != model) {
            checkUnique(dto, model);
        }
    }

    /**
     * 验证唯一性索引
     *
     * @param dto   页面对象
     * @param model 根据约束字段查询出来的数据库对象
     */
    private void checkUnique(PersonDTO dto, Person model) {
        if (!StringUtils.hasLength(dto.getPersonId())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
        if (!dto.getPersonId().equals(model.getPersonId())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(Person model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getPersonId()));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_SYS_PERSON, model.getPersonId(), model.getOrgId()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<Person> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getPersonId())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
        List<String> uniqueIds = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_SYS_PERSON, model.getPersonId(), model.getOrgId())).collect(toList());
        if (!uniqueIds.isEmpty()) {
            redisTemplateUtil.deleteByKey(uniqueIds);
            uniqueIds.clear();
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public PersonDTO modelToDto(Person model) {
        if (null == model) {
            return null;
        }
        final PersonDTO dto = new PersonDTO();
        dto.setPersonId(model.getPersonId());
        dto.setAccount(model.getAccount());
        dto.setPassword(model.getPassword());
        dto.setPersonName(model.getPersonName());
        dto.setIdCard(model.getIdCard());
        dto.setPhone(model.getPhone());
        dto.setSex(model.getSex());
        dto.setEmail(model.getEmail());
        dto.setAvatar(model.getAvatar());
        dto.setUserStatus(model.getUserStatus());
        dto.setAddTime(model.getAddTime());
        dto.setUpdateTime(model.getUpdateTime());
        dto.setOrgId(model.getOrgId());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public Person dtoToModel(PersonDTO dto) {
        if (null == dto) {
            return null;
        }
        final Person model = new Person();
        model.setPersonId(dto.getPersonId());
        model.setAccount(dto.getAccount());
        model.setPassword(dto.getPassword());
        model.setPersonName(dto.getPersonName());
        model.setIdCard(dto.getIdCard());
        model.setPhone(dto.getPhone());
        model.setSex(dto.getSex());
        model.setEmail(dto.getEmail());
        model.setAvatar(dto.getAvatar());
        model.setUserStatus(dto.getUserStatus());
        model.setAddTime(dto.getAddTime());
        model.setUpdateTime(dto.getUpdateTime());
        model.setOrgId(dto.getOrgId());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(PersonDTO dto) {
        dto.setUserStatusDisplay(MbUtil.idToDisplay(dto.getUserStatus()));
        dto.setOrgIdDisplay(orgService.idToDisplay(dto.getOrgId()));
        dto.setSexDisplay(MbUtil.idToDisplay(dto.getSex()));
        dto.setAvatarDisplay(FileConfirmUtil.getImageFile(dto.getAvatar()));
//        final List<PersonRoleDto> personRoles = personRoleService.getListByPersonIdDto(dto.getPersonId());
//        if (!personRoles.isEmpty()) {
//            dto.setPersonRoles(personRoles);
//        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<PersonDTO> modelToDtoList(List<Person> list) {
        if (null == list) {
            return Collections.emptyList();
        }
        return list.stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<Person> dtoToModelList(List<PersonDTO> list) {
        if (null == list) {
            return Collections.emptyList();
        }
        return list.stream().map(this::dtoToModel).collect(toList());
    }

    public QueryWrapper<Person> createQueryWrapper(PersonDTO PersonDTO) {
        return createQueryWrapper(PersonDTO, "");

    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param PersonDTO 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<Person> createQueryWrapper(PersonDTO PersonDTO, String tableAlias) {
        final QueryWrapper<Person> queryWrapper = new QueryWrapper<>();
        if (null != PersonDTO) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(PersonDTO.getOrgId())) {
                queryWrapper.eq(tableAlias + Constants.ORG_ID, PersonDTO.getOrgId());
            }
            if (StringUtils.hasLength(PersonDTO.getAccount())) {
                queryWrapper.eq(tableAlias + "account", PersonDTO.getAccount());
            }
            if (StringUtils.hasLength(PersonDTO.getIdCard())) {
                queryWrapper.eq(tableAlias + "id_card", PersonDTO.getIdCard());
            }
            if (StringUtils.hasLength(PersonDTO.getPersonName())) {
                queryWrapper.like(tableAlias + "person_name", PersonDTO.getPersonName());
            }
            if (StringUtils.hasLength(PersonDTO.getPhone())) {
                queryWrapper.eq(tableAlias + "phone", PersonDTO.getPhone());
            }
            if (StringUtils.hasLength(PersonDTO.getSex())) {
                queryWrapper.eq(tableAlias + "sex", PersonDTO.getSex());
            }
            if (null != PersonDTO.getUserStatus()) {
                queryWrapper.eq(tableAlias + "user_status", PersonDTO.getUserStatus());
            }
            if (StringUtils.hasLength(PersonDTO.getBeginTime())) {
                queryWrapper.apply("date_format(" + tableAlias + "add_time,'%Y-%m-%d') >= {0}", PersonDTO.getBeginTime());
            }
            if (StringUtils.hasLength(PersonDTO.getEndTime())) {
                queryWrapper.apply("date_format(" + tableAlias + "add_time,'%Y-%m-%d') <= {0}", PersonDTO.getEndTime());
            }
        }
        queryWrapper.orderByAsc(tableAlias + Constants.ORG_ID);
//        queryWrapper.orderByAsc(tableAlias + "person_name");
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<Person> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<Person> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(Person::getPersonId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    /**
     * 判断id是否存在
     *
     * @param id 主键
     */
    @Transactional(readOnly = true)
    public void checkId(String id) {
        if (Boolean.FALSE.equals(isExistsById(id))) {
            throw new ApiException("人员ID不存在");
        }
    }


    /**
     * 获得人员名称
     *
     * @param personId 人员ID
     * @return 姓名
     */
    @Transactional(readOnly = true)
    public String idToDisplay(String personId) {
        String display = "";
        if (StringUtils.hasLength(personId)) {
            final Person person = getById(personId);
            display = (null == person ? "" : person.getPersonName());
        }
        return display;
    }

    /**
     * 查询机构下面的人员列表
     *
     * @param orgId 机构ID
     * @return 人员列表
     */
    public List<Person> getListByOrgId(String orgId) {
        final PersonDTO query = new PersonDTO();
        query.setOrgId(orgId);
        QueryWrapper<Person> queryWrapper = createQueryWrapper(query);
        final List<Person> personList = list(queryWrapper);
        query.freeData();
        queryWrapper.clear();
        return personList;
    }
}